package com.xia.fifter;

import com.xia.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;

/**
 * 令牌校验过滤器
 */
@Slf4j
@WebFilter(urlPatterns = "/user/*")
@Component
public class TokenFilter implements Filter {
    // 实现Filter接口中的doFilter方法，用于执行过滤逻辑
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 获取请求Url
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 从请求头中获取token
        String token = request.getHeader("Authorization");

        // 检查token是否存在且格式正确
        if (token != null && token.startsWith("Bearer ")) {
            // 去除"Bearer "前缀，获取纯token信息
            token = token.substring(7);
            // 使用JwtUtils工具类解析token，获取用户名
            String username = JwtUtils.parseJWT(token);

            // 创建认证令牌对象，用于Spring Security进行用户认证
            UsernamePasswordAuthenticationToken authentication =
                    new UsernamePasswordAuthenticationToken(username, null, new ArrayList<>());

            // 将认证信息设置到SecurityContext中，完成用户认证
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }

        // 继续执行其他过滤器或请求的业务逻辑
        filterChain.doFilter(request, response);
    }
}

